package com.dhecp.project.system.controller;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

import org.apache.shiro.authz.annotation.Logical;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.ModelAndView;

import com.dhecp.common.annotation.Log;
import com.dhecp.common.annotation.RepeatSubmit;
import com.dhecp.common.config.Global;
import com.dhecp.common.core.controller.BaseController;
import com.dhecp.common.core.domain.AjaxResult;
import com.dhecp.common.core.page.TableDataInfo;
import com.dhecp.common.enums.BusinessType;
import com.dhecp.common.utils.TypeUtils;
import com.dhecp.common.utils.file.FileUploadUtils;
import com.dhecp.core.constant.ModuleTable;
import com.dhecp.core.enums.DataLimitType;
import com.dhecp.core.enums.UserLevelType;
import com.dhecp.core.layui.GridColumnsPropertyModel;
import com.dhecp.core.utils.ExportExcelUtils;
import com.dhecp.framework.util.ShiroUtils;
import com.dhecp.project.common.service.ButtonStateService;
import com.dhecp.project.system.domain.SysDictionaryForExport;
import com.dhecp.project.system.domain.SysRoleInfo;
import com.dhecp.project.system.domain.SysUserInfo;
import com.dhecp.project.system.domain.SysUserInfoSimple;
import com.dhecp.project.system.service.SysDictionaryForFieldService;
import com.dhecp.project.system.service.SysRoleInfoService;
import com.dhecp.project.system.service.SysUserInfoService;

/**
 * 用户信息 控制层
 * @author DH-Xxj
 * @version 2019年10月10日
 */
@Controller
@RequestMapping("/system/user")
public class SysUserController extends BaseController{
    private String prefix = "system/user";
    private String moduleTable = ModuleTable.USER_INFO;
    private String moduleTableForRole = ModuleTable.ROLE_INFO;

    @Autowired
    private SysUserInfoService userInfoService;

    @Autowired
    private SysRoleInfoService roleInfoService;

    @Autowired
    private SysDictionaryForFieldService dictionaryForFieldService;

    @Autowired
    private GridColumnsPropertyModel gridColumnsPropertyModel;
	
	@Autowired
	private ButtonStateService buttonStateService;

    /**
     * 打开用户列表
     * @param 
     * @return ModelAndView
     * @author DH-Xxj
     */
    @RequiresPermissions("system:user:view")
    @GetMapping()
    public ModelAndView userInfoList(@RequestParam Map<String, Object> params){
    	params.put("moduleTable", moduleTable);
    	params.put("entity", new SysUserInfo()); //生成表格gridColumns对应的实体，用于获取实体属性生成表格字段

    	if (!Global.isCsLoginEnabled()){ //读取配置文件，若未开启仅CS登录开关，则列表隐藏 始终允许浏览器登录 字段
    		Map<String, String> hiddenFieldsMap = new HashMap<String, String>();
    		hiddenFieldsMap.put("browserlogin", "browserlogin");
    		hiddenFieldsMap.put("browserlogintext", "browserlogintext");
        	params.put("hiddenFieldsMap", hiddenFieldsMap);
    	}
    	
    	Subject userSubject = ShiroUtils.getSubject();
    	Integer toolBarWidth = 0;
    	if (userSubject.isPermitted("system:user:delete")){	//当前登录用户主体是否有删除的权限
        	params.put("checkBox", "yes"); //生成表格gridColumns时包含复选
        	toolBarWidth = toolBarWidth + 50;
    	}
    	if (userSubject.isPermitted("system:user:edit")){ //当前登录用户主体是否有修改的权限(编辑、重置密码、分配角色、设置权限)
    		toolBarWidth = toolBarWidth + 265;
    	}
    	params.put("toolBarWidth", toolBarWidth);

    	Object importFields = null;    
        ModelAndView mv = this.getModelAndView();
        AjaxResult ajaxResult = new AjaxResult();
        Map<String, Object> dictionaryForFieldMap = new HashMap<String, Object>();
        try{
        	importFields = dictionaryForFieldService.queryFieldFrontImport(params); //导入模板
            dictionaryForFieldMap = dictionaryForFieldService.queryFieldAttributesMap(params);
            if (dictionaryForFieldMap.isEmpty()){
                ajaxResult = AjaxResult.error("未获取到字段属性。");
            }else{
                ajaxResult = AjaxResult.success("数据获取成功。");
            }
        }
        catch(Exception e){
            ajaxResult = AjaxResult.error(this.getExceptionMessage(e));
        }
        mv.addObject("fields", TypeUtils.mapToJson(dictionaryForFieldMap));
        mv.addObject("ajaxResult", ajaxResult);
        mv.addObject("gridColumns", gridColumnsPropertyModel.queryGridColumnsPropertyModel(params)); 
        mv.addObject("importFields",importFields);				//导入字段模板
        mv.addObject("moduleTable", moduleTable);
        mv.setViewName(prefix + "/user");
        return mv;
    }
    
    /**
     * 打开用户选择列表，简单用户信息，用于选择用户
     * @param pagetype ：必要参数【页面类型：radio（单选），checkbox（多选）】
     * @param selectedUser ：已选中的用户编号字符串，示例：0000,1001,1002
     * @return ModelAndView
     * @author DH-Xxj
     */
    @RequiresPermissions("system:user:view")
    @GetMapping("/userselect")
    public ModelAndView userInfoSelectList(@RequestParam Map<String, Object> params){
        ModelAndView mv = this.getModelAndView();
        params.put("moduleTable", moduleTable);
        mv = this.gotoModelAndViewErrorPage(params, "pagetype","页面类型：radio（单选），checkbox（多选）");
        if (mv.isEmpty()){
        	String pagetype = "checkbox".equals(params.get("pagetype").toString())?"checkbox":"radio";
        	if (params.get("selectedUser") != null && params.get("selectedUser") != ""){
        		String selectedUser = params.get("selectedUser").toString();
            	mv.addObject("selectedUser", selectedUser);
        	}
        	mv.addObject("pagetype", pagetype);
            mv.setViewName(prefix + "/user_select");	
        }
        return mv;
    }
    
    /**
     * 打开用户选择列表（通用页面）
     */
    @GetMapping("/select")
    public ModelAndView selectList(@RequestParam Map<String, Object> params){
    	params.put("moduleTable", moduleTable);
    	params.put("entity", new SysUserInfo()); //生成表格gridColumns对应的实体，用于获取实体属性生成表格字段
    	params.put("toolBarWidth", 0);
    	if(params.get("pagetype") !=null && params.get("pagetype").toString().equalsIgnoreCase("checkbox"))params.put("checkBox", "yes");
        else params.put("radio", "yes");
        ModelAndView mv = this.getModelAndView();
        AjaxResult ajaxResult = new AjaxResult();
        Map<String, Object> dictionaryForFieldMap = new HashMap<String, Object>();
        
        mv.addObject("fields", TypeUtils.mapToJson(dictionaryForFieldMap));
        mv.addObject("ajaxResult", ajaxResult);
        mv.addObject("gridColumns", gridColumnsPropertyModel.queryGridColumnsPropertyModel(params));
        mv.addObject("prefix", prefix);
        mv.addObject("moduleTable", moduleTable);
        mv.setViewName("common/select");
        return mv;
    }

    /** 打开同步企业微信页面
     * @return ModelAndView
     */
    @RequiresPermissions("system:user:add")
    @GetMapping("/syncwechat")
    public ModelAndView syncWeChat(@RequestParam Map<String, Object> params){
        ModelAndView mv = this.getModelAndView();
        mv.setViewName(prefix + "/sync_wechat");
        return mv;
    }

    /**
     * 打开用户新增页
     * @param params
     * @return ModelAndView
     * @author DH-Xxj
     */
    @RequiresPermissions("system:user:add")
    @GetMapping("/add")
    public ModelAndView userInfoAdd(@RequestParam Map<String, Object> params){
    	params.put("moduleTable", moduleTable);
        ModelAndView mv = this.getModelAndView();
        AjaxResult ajaxResult = new AjaxResult();
        Map<String,Object> userLevelMap = ShiroUtils.getUserLevelMap(1);
        Map<String, Object> dictionaryForFieldMap = new HashMap<String, Object>();
        Map<String, Object> buttonMap = new HashMap<String, Object>();
        Map<String, Object> buttonState = new HashMap<String, Object>();
        try{
            dictionaryForFieldMap = dictionaryForFieldService.queryFieldAttributesMap(params);
            buttonMap.put("moduleTable", ModuleTable.PERSONNEL_DA_XX);
            buttonState = buttonStateService.getButtonStateObjectForUser(buttonMap);
            if (dictionaryForFieldMap.isEmpty()){
                ajaxResult = AjaxResult.error("未获取到字段属性。");
            }else{
                ajaxResult = AjaxResult.success("数据获取成功。");
            }
        }
        catch(Exception e){
            ajaxResult = AjaxResult.error(this.getExceptionMessage(e));
        }
        mv.addObject("pageType","add");
        mv.addObject("fields", TypeUtils.mapToJson(dictionaryForFieldMap));
        mv.addObject("ajaxResult", ajaxResult);
        mv.addObject("userLevelMap", userLevelMap);
        mv.addObject("buttonState", TypeUtils.mapToJson(buttonState));		//按钮状态：（可用：enable，禁用：disable，隐藏：hidden）
        mv.setViewName(prefix + "/user_add");
        return mv;
    }
    
    /**
     * 打开用户修改页
     * @param params userId:必要参数，用户编号
     * @return ModelAndView
     * @author DH-Xxj
     */
    @RequiresPermissions("system:user:edit")
    @GetMapping("/edit")
    public ModelAndView userInfoEdit(@RequestParam Map<String, Object> params){
    	params.put("moduleTable", moduleTable);
        ModelAndView mv = this.getModelAndView();
        AjaxResult ajaxResult = new AjaxResult();
        Map<String,Object> userLevelMap = ShiroUtils.getUserLevelMap(1);
        Map<String, Object> dictionaryForFieldMap = new HashMap<String, Object>();
        Map<String, Object> buttonMap = new HashMap<String, Object>();
        Map<String, Object> buttonState = new HashMap<String, Object>();
        SysUserInfo sysUserInfo = new SysUserInfo();
        List<SysUserInfoSimple> relevantDAUserList = new ArrayList<SysUserInfoSimple>();
        mv = this.gotoModelAndViewErrorPage(params, "userId", "用户编号");
        if (mv.isEmpty()){
            try{
                dictionaryForFieldMap = dictionaryForFieldService.queryFieldAttributesMap(params);
                buttonMap.put("moduleTable", ModuleTable.PERSONNEL_DA_XX);
                buttonState = buttonStateService.getButtonStateObjectForUser(buttonMap);
                if (dictionaryForFieldMap.isEmpty()){
                    ajaxResult = AjaxResult.error("未获取到字段属性。");
                }else{
                	sysUserInfo = userInfoService.queryByUserId(params.get("userId").toString());
                	if (sysUserInfo == null){
                		ajaxResult = AjaxResult.error("没有查到用户[" + params.get("userId").toString() + "]。");
                	}else{
                    	ajaxResult = AjaxResult.success("数据获取成功。");
                    	String daNid = sysUserInfo.getDaNid();
                        Map<String, Object> nidMap = new HashMap<String, Object>();
                    	if (daNid != null && !"".equals(daNid)){
                    		nidMap.put("nid", daNid);
                    		nidMap.put("daNid", daNid);
                        	relevantDAUserList = userInfoService.queryUserSimpleListByDaNid(nidMap);
                    	}
                	}
                }
            }
            catch(Exception e){
                ajaxResult = AjaxResult.error(this.getExceptionMessage(e));
            }
            mv.addObject("pageType","edit");
            mv.addObject("sysUserInfo",sysUserInfo);					//用户信息
            mv.addObject("relevantDAUserList",relevantDAUserList);		//档案相关账号列表
            mv.addObject("fields", TypeUtils.mapToJson(dictionaryForFieldMap));
            mv.addObject("ajaxResult", ajaxResult);
            mv.addObject("userLevelMap", userLevelMap);
            mv.addObject("buttonState", TypeUtils.mapToJson(buttonState));	//按钮状态：（可用：enable，禁用：disable，隐藏：hidden）
            mv.addObject("isCsLoginEnabled",Global.isCsLoginEnabled());		//读取配置文件，若未开启仅CS登录开关，则隐藏 始终允许浏览器登录 字段
            mv.setViewName(prefix + "/user_edit");
        }
        return mv;
    }
    
    /**
     * 打开用户详情页（仅显示信息，不提供修改）
     * @param params userId:必要参数，用户编号
     * @return ModelAndView
     * @author DH-Xxj
     */
    @RequiresPermissions("system:user:view")
    @GetMapping("/view")
    public ModelAndView userInfoView(@RequestParam Map<String, Object> params){
    	params.put("moduleTable", moduleTable);
        ModelAndView mv = this.getModelAndView();
        AjaxResult ajaxResult = new AjaxResult();
        SysUserInfo userInfo = new SysUserInfo();
        List<SysRoleInfo> sysRoleInfoList = new ArrayList<SysRoleInfo>();
        List<SysUserInfoSimple> relevantDAUserList = new ArrayList<SysUserInfoSimple>();
        Map<String,Object> userLevelMap = TypeUtils.EnumToMap(UserLevelType.class);
        mv = this.gotoModelAndViewErrorPage(params, "userId", "用户编号");
        if (mv.isEmpty()){
            try{
            	userInfo = userInfoService.queryByUserId(params.get("userId").toString());
            	if (userInfo == null){
            		ajaxResult = AjaxResult.error("没有查到用户[" + params.get("userId").toString() + "]。");
            	}else{
                	if (userLevelMap.get(userInfo.getUserLevel().toString()) != null){
                		userInfo.setUserLeveltext(userLevelMap.get(userInfo.getUserLevel().toString()).toString());
                	}
                	String daNid = userInfo.getDaNid();
                    Map<String, Object> nidMap = new HashMap<String, Object>();
                	if (daNid != null && !"".equals(daNid)){
                		nidMap.put("nid", daNid);
                		nidMap.put("daNid", daNid);
                    	relevantDAUserList = userInfoService.queryUserSimpleListByDaNid(nidMap);
                	}
                	ajaxResult = AjaxResult.success("数据获取成功。");
            	}
            	params.put("moduleTable", moduleTableForRole);
            	sysRoleInfoList = roleInfoService.queryRoleInfoListByUserId(params);
            }
            catch(Exception e){
                ajaxResult = AjaxResult.error(this.getExceptionMessage(e));
            }
            mv.addObject("pageType","edit");
            mv.addObject("sysUserInfo",userInfo);						//用户信息
            mv.addObject("sysRoleInfoList",sysRoleInfoList);			//角色列表
            mv.addObject("relevantDAUserList",relevantDAUserList);		//档案相关账号列表
            mv.addObject("ajaxResult", ajaxResult);
            mv.setViewName(prefix + "/user_view");
        }
        return mv;
    }


    /**
     * 打开修改头像页
     * @param params userId:必要参数，用户编号
     * @return ModelAndView
     * @author kimiloo
     */
    @RequiresPermissions("system:user:view")
    @GetMapping("/avatar")
    public ModelAndView avatar(@RequestParam Map<String, Object> params){
    	params.put("moduleTable", moduleTable);
        ModelAndView mv = this.getModelAndView();
        AjaxResult ajaxResult = new AjaxResult();
        SysUserInfo userInfo = new SysUserInfo();
        mv = this.gotoModelAndViewErrorPage(params, "userId", "用户编号");
        if (mv.isEmpty()){
            try{
            	userInfo = userInfoService.queryByUserId(params.get("userId").toString());
            	if (userInfo == null){
            		ajaxResult = AjaxResult.error("没有查到用户[" + params.get("userId").toString() + "]。");
            	}else{
                	ajaxResult = AjaxResult.success("数据获取成功。");
            	}
            }
            catch(Exception e){
                ajaxResult = AjaxResult.error(this.getExceptionMessage(e));
            }
            mv.addObject("sysUserInfo",userInfo);
            mv.addObject("ajaxResult", ajaxResult);
            mv.setViewName(prefix + "/avatar");
        }
        return mv;
    }


    /**
     * 打开用户密码修改页
     * @param userId:必要参数，用户编号
     * @param upType：修改类型（"resetpwd":重置密码，无需提供原密码；"changepwd":修改密码，需要提供原密码）
     * @return ModelAndView
     * @author DH-Xxj
     */
//    @RequiresPermissions("system:user:edit")
    @GetMapping("/passwordedit")
    public ModelAndView userPassWordEdit(@RequestParam Map<String, Object> params){
        ModelAndView mv = this.getModelAndView();
        String upType = "";
        mv = this.gotoModelAndViewErrorPage(params, "userId", "用户编号");
        if (mv.isEmpty()){
        	if (params.get("upType") == null || params.get("upType") == "" || !"resetpwd".equals(params.get("upType").toString())){
        		upType = "changepwd";	//修改密码，需要提供原密码
        	}else{
        		upType = "resetpwd";
        	}

            mv.addObject("userId",params.get("userId").toString());
            mv.addObject("upType", upType);
            mv.setViewName(prefix + "/user_resetpwd");
        }
        return mv;
    }
    
    /**
     * 打开用户功能权限分配页面
     * @param userId 必要参数：用户编号
     * @return ModelAndView
     * @author DH-Xxj
     */
    @RequiresPermissions(value={"system:user:view","system:user:edit"},logical=Logical.AND)
    @GetMapping("/userandrolejurisdictionformodule")
    public ModelAndView userAndRoleJurisdictionForModuleEdit(@RequestParam Map<String, Object> params){
        ModelAndView mv = this.getModelAndView();
        mv = this.gotoModelAndViewErrorPage(params, "userId", "用户编号【userId】");
        if (mv.isEmpty()){            
            mv.addObject("vType", "user");	//role:角色权限分配,user:用户权限分配
            mv.addObject("pid", params.get("userId"));	//分配权限的用户
            mv.setViewName("system/userandrolejurisdiction/userandrolejurisdictionformodule_edit");        	
        }
        return mv;
    }
    
    /**
     * 打开用户数据权限分配页面
     * @param userId 必要参数：用户编号
     * @return ModelAndView
     * @author DH-Xxj
     */
    @RequiresPermissions(value={"system:user:view","system:user:edit"},logical=Logical.AND)
    @GetMapping("/userandrolejurisdictionfordata")
    public ModelAndView userAndRoleJurisdictionForDataEdit(@RequestParam Map<String, Object> params){
        ModelAndView mv = this.getModelAndView();
        mv = this.gotoModelAndViewErrorPage(params, "userId", "用户编号【userId】");
        if (mv.isEmpty()){
        	Map<String,Object> dataLimitMap = TypeUtils.EnumToMap(DataLimitType.class);
        	dataLimitMap.remove("OperateData"); //去除运营公司权限
            mv.addObject("dataLimitMap", dataLimitMap); //查询条件下拉框数据
            mv.addObject("vType", "user");	//role:角色权限分配,user:用户权限分配
            mv.addObject("pid", params.get("userId"));	//分配权限的用户
            mv.setViewName("system/userandrolejurisdiction/userandrolejurisdictionfordata_edit");        	
        }
        return mv;
    }
    
    /**
     * 查询已选中的用户列表
     * @param selectedUser ：已选中的用户编号字符串，示例：0000,1001,1002
     * @return ModelAndView
     * @author DH-Xxj
     */
//    @RequiresPermissions("system:user:list")
    @GetMapping("/listselect")
    @ResponseBody
    public TableDataInfo userInfoSelectListJson(@RequestParam Map<String, Object> params){
        params.put("moduleTable", moduleTable);
		List<SysUserInfoSimple> list = new ArrayList<SysUserInfoSimple>();
    	if (params.get("selectedUser") != null && params.get("selectedUser") != ""){
    		String wherestrhand = "t1.userId in ('" + params.get("selectedUser").toString().replace(",", "','") + "')";
    		params.put("wherestrhand", wherestrhand);
    		try{
    			list = userInfoService.queryUserSimpleList(params);
    		}catch(Exception e){
    			return getDataTable(this.getExceptionMessage(e).toString());
    		}
    	}else{
    		return getDataTable("请传入已选中的用户编号字符串（selectedUser），取值示例：0000,1001,1002");
    	}
        return getDataTable(list);
    }

    /**
     * 按条件查询用户列表
     * @param serachType 查询类型：serachType='simple'时查询精简用户信息，不传入时查询用户详细信息
     * @return GridDataModel
     * @throws Exception
     * @author DH-Xxj
     */
    @RequiresPermissions("system:user:list")
    @GetMapping("/list")
    @ResponseBody
    public TableDataInfo userInfoListJson(@RequestParam Map<String, Object> params){
    	params.put("moduleTable", moduleTable);
        try {
        	if (params.get("serachType") != null && "simple".equals(params.get("serachType").toString().toLowerCase())){
        		//查询精简用户列表
                List<SysUserInfoSimple> list = new ArrayList<SysUserInfoSimple>();
        		list = userInfoService.queryUserSimpleList(params);
                return getDataTable(list);
        	}else{
        		//查询详细用户列表
                List<SysUserInfo> list = new ArrayList<SysUserInfo>();
                Map<String,Object> userLevelMap = TypeUtils.EnumToMap(UserLevelType.class);
                list = userInfoService.queryUserList(params);
                for (SysUserInfo userInfo : list){
                	if (userLevelMap.get(userInfo.getUserLevel().toString()) != null){
                		userInfo.setUserLeveltext(userLevelMap.get(userInfo.getUserLevel().toString()).toString());
                	}
                }
                return getDataTable(list);
        	}
        } catch (Exception e) {
            e.printStackTrace();
            return getDataTable(this.getExceptionMessage(e).toString());
        }
    }
    
    /**
     * 按条件查询指定角色类型（客户销售）用户列表 —— 精简数据
     * @param roleType 必要参数，示例：customerGUser（客户销售）、All（查询全部）、SW（商务类角色）、（XS）销售类角色，具体类型在表TS_RoleGuidType中查看和配置
     * @param gClient 可选参数，客户编号，当roleType=‘customerGUser’时，必需传对应客户编号
     * @return
     * @author DH-Xxj
     */
    @GetMapping("/roletypelist")
    @ResponseBody
    public TableDataInfo roleTypeUserSimpleList(@RequestParam Map<String, Object> params){
    	params.put("moduleTable", moduleTable);
        try {
            List<SysUserInfoSimple> list = new ArrayList<SysUserInfoSimple>();
    		list = userInfoService.queryRoleTypeUserSimpleList(params);
            return getDataTable(list);
        } catch (Exception e) {
            e.printStackTrace();
            return getDataTable(this.getExceptionMessage(e).toString());
        }
    }

    /**
     * 导出用户列表
     * @param params
     * @return
     * @throws Exception
     * @author DH-Xxj
     */
    @Log(title = "用户导出", businessType = BusinessType.EXPORT)
    @RequiresPermissions("system:user:export")
    @GetMapping("/export")
    @ResponseBody
    public AjaxResult export(@RequestParam Map<String, Object> params) throws Exception{
		params.put("moduleTable", moduleTable);
    	params.put("entity", new SysUserInfo()); 
        List<SysUserInfo> list = userInfoService.queryUserList(params);

		params.put("moduleTable", moduleTable);
    	params.put("getFieldAttributesType", "export");
    	List<SysDictionaryForExport> fieldList = dictionaryForFieldService.queryExportFieldList(params);
        ExportExcelUtils<SysUserInfo> util = new ExportExcelUtils<SysUserInfo>(moduleTable,new SysUserInfo());
        return util.exportExcel(list, fieldList, "用户列表", "export");
    }

    /**
     * 导出用户导入模板
     * @param params
     * @return
     * @throws Exception
     * @author DH-Xxj
     */
    @RequiresPermissions("system:user:import")
    @Log(title = "用户模板导出", businessType = BusinessType.EXPORT)
    @GetMapping("/exporttemplate")
    @ResponseBody
    @RepeatSubmit
    public AjaxResult exportTemplate(@RequestParam Map<String, Object> params) throws Exception {
		params.put("moduleTable", moduleTable);
    	params.put("entity", new SysUserInfo()); 
    	params.put("getFieldAttributesType", "template");

    	List<SysDictionaryForExport> fieldList = dictionaryForFieldService.queryExportFieldList(params);
        ExportExcelUtils<SysUserInfo> util = new ExportExcelUtils<SysUserInfo>(moduleTable,new SysUserInfo());
        return util.exportExcel(null, fieldList, "用户导入模板", "template");
    }
    
    /**
     * 分配用户角色
     * @param params
     * @return Map
     * @author DH-Xxj
     */
    @RequiresPermissions("system:role:list")
    @GetMapping("/userbindrolelist")
    @ResponseBody
    public Map<String,Object> roleBindList(@RequestParam Map<String, Object> params){
    	Map<String,Object> returnMap = new LinkedHashMap<String,Object>();
        if (params.get("userId") == null || params.get("userId") == ""){
        	returnMap.put("code", "500");
        	returnMap.put("msg", "请输入要查询的用户编号【userId】。");
        	return returnMap;
        }
        List<Map<String,String>> dataAll = new ArrayList<Map<String,String>>();
        List<String> dataSelect = new ArrayList<String>();
        try {
        	dataAll = roleInfoService.queryRoleToMapList(params);
        	dataSelect = roleInfoService.queryUserBindRoleList(params);
        	returnMap.put("code", "0");
        	returnMap.put("msg", "");
        	returnMap.put("dataAll", dataAll);
        	returnMap.put("dataSelect", dataSelect);
        } catch (Exception e) {
        	returnMap.put("code", "500");
        	returnMap.put("msg", this.getExceptionMessage(e).toString());         
        }
        return returnMap;
    	
    }
    
    /**
     * 查询指定用户未分配的角色列表
     * @param userId 必要参数：用户编号
     * @return TableDataInfo
     * @author DH-Xxj
     */
    @RequiresPermissions("system:role:list")
    @GetMapping("/userlackrolelist")
    @ResponseBody
    public TableDataInfo roleList(@RequestParam Map<String, Object> params){
        if (params.get("userId") == null || params.get("userId") == ""){
        	return getDataTable("请输入要查询的用户编号【userId】。");
        }
    	params.put("moduleTable", moduleTableForRole);
        List<SysRoleInfo> list = new ArrayList<SysRoleInfo>();
        try {
            list = roleInfoService.queryLackRoleListByUserId(params);
        } catch (Exception e) {
            return getDataTable(this.getExceptionMessage(e).toString());            
        }
        return getDataTable(list);
    }
    
    /**
     * 查询指定用户已分配的角色列表
     * @param userId 必要参数：用户编号
     * @return TableDataInfo
     * @author DH-Xxj
     */
    @RequiresPermissions("system:user:list")
    @GetMapping("/userrolelist")
    @ResponseBody
    public TableDataInfo userRoleList(@RequestParam Map<String, Object> params){
        if (params.get("userId") == null || params.get("userId") == ""){
        	return getDataTable("请输入要查询的用户编号【userId】。");
        }
    	params.put("moduleTable", moduleTableForRole);
        List<SysRoleInfo> list = new ArrayList<SysRoleInfo>();
        try {
            list = roleInfoService.queryRoleInfoListByUserId(params);
        } catch (Exception e) {
            return getDataTable(this.getExceptionMessage(e).toString());            
        }
        return getDataTable(list);
    }

    /**
     * 新增用户——数据提交
     * @param userInfoItems 必要参数：对应实体类的json格式字符串
     * @return AjaxResult
     * @author DH-Xxj
     */
    @RequiresPermissions("system:user:add")
    @Log(title = "新增用户", businessType = BusinessType.INSERT)
    @PostMapping("/addpost")
    @ResponseBody
    @RepeatSubmit
    public AjaxResult userInfoAddPost(@RequestParam Map<String, Object> params) {
        AjaxResult ajaxResult = new AjaxResult();
        if (params.get("userInfoItems") == null || params.get("userInfoItems") == ""){
        	return AjaxResult.error("缺少参数userInfoItems【对应实体类的json格式字符串】。");
        }
        try {
            ajaxResult= userInfoService.insertUserInfo(params);
        }catch (Exception e) {
            ajaxResult = AjaxResult.error(this.getExceptionMessage(e));
        }
        return ajaxResult;
    }
    
    /***
    * 修改头像
    * @param avatarfile 头像文件
    * @return AjaxResult
    * @author kimiloo
    */
	@Log(title = "修改头像", businessType = BusinessType.UPDATE)
	@PostMapping("/updateAvatar")
	@ResponseBody
	public AjaxResult updateAvatar(@RequestParam("avatarfile") MultipartFile uploadfile){
		Map<String, Object> params = new HashMap<String, Object>();
		Map<String, Object> userInfoItems = new HashMap<String, Object>();
		try{
	    	if (!uploadfile.isEmpty()){
	    		// 上传文件路径
	            String fileDirPath = Global.getUploadPath();
	            fileDirPath = Global.getProfile() + "/avatar";
	            // 上传并返回新文件名称
	            String filePath = FileUploadUtils.upload(fileDirPath, uploadfile);
	            
	            params.put("upType", "upuserpicture");
	            userInfoItems.put("userPicture", filePath);
	            userInfoItems.put("userId", ShiroUtils.getMandatorId());
	            Object userInfoItemsObj = TypeUtils.mapToJson(userInfoItems);
	            params.put("userInfoItems", "[" + userInfoItemsObj.toString() + "]");
	            
	            AjaxResult ajaxResult = new AjaxResult();
	            try {
	                ajaxResult= userInfoService.updateUserInfo(params);
	            }catch (Exception e) {
	                ajaxResult = AjaxResult.error(this.getExceptionMessage(e));
	            }
	            return ajaxResult;
	       }
	       return error();
		}
		catch (Exception e)
		{
	       return error(e.getMessage());
		}
	}
    /**
     * 分配用户角色——数据提交
     * @param userId 当前分配角色的用户编码
     * @param infoItems 角色对应实体类的json格式字符串(必要键值：角色编码[guid])
     * @return AjaxResult
     * @author DH-Xxj
     */
    @RequiresPermissions("system:user:edit")
    @Log(title = "分配用户角色", businessType = BusinessType.UPDATE)
    @PostMapping("/adduserrolepost")
    @ResponseBody
    @RepeatSubmit
    public AjaxResult userRoleaddPost(@RequestParam Map<String, Object> params) {
//    	params.put("userId", "1111");
//    	params.put("infoItems", "[{guid:111},{guid:123},{guid:333}]");
//    	params.put("infoItems", "[]");
        AjaxResult ajaxResult = new AjaxResult();
        if (params.get("userId") == null || params.get("userId") == ""){
        	return AjaxResult.error("缺少参数userId【当前分配角色的用户编码】。");
        }
        if (params.get("infoItems") == null || params.get("infoItems") == ""){
        	return AjaxResult.error("缺少参数infoItems【角色对应实体类的json格式字符串(必要键值：角色编码[guid])】。");
        }
        try {
            ajaxResult= userInfoService.insertUserRole(params);
        }catch (Exception e) {
            ajaxResult = AjaxResult.error(this.getExceptionMessage(e));
        }
        return ajaxResult;
    }

    /**
     * 修改用户信息——数据提交
     * @param userInfoItems 必要参数：对应实体类的json格式字符串
     * @param upType 必要参数：修改类型（修改用户信息：upuser，修改用户基础信息：upuserbaseinfo，修改用户皮肤：upskin，修改档案照片：upuserphoto，修改用户头像：upuserpicture）
     * @return AjaxResult
     * @author DH-Xxj
     */
    @RequiresPermissions("system:user:edit")
    @Log(title = "修改用户信息", businessType = BusinessType.UPDATE)
    @PostMapping("/editpost")
    @ResponseBody
    @RepeatSubmit
    public AjaxResult userInfoEditPost(@RequestParam Map<String, Object> params) {
        AjaxResult ajaxResult = new AjaxResult();
        if (params.get("userInfoItems") == null || params.get("userInfoItems") == ""){
        	return AjaxResult.error("缺少参数userInfoItems【对应实体类的json格式字符串】。");
        }
        try {
            ajaxResult= userInfoService.updateUserInfo(params);
        }catch (Exception e) {
            ajaxResult = AjaxResult.error(this.getExceptionMessage(e));
        }
        return ajaxResult;
    }

    /**
     * 修改 始终允许浏览器登录 字段——数据提交
     * @param infoItems 对应实体类的json格式字符串，包含属性（userId：用户编号， browserLogin：始终允许浏览器登录）
     * @return AjaxResult
     * @author DH-Xxj
     */
    @RequiresPermissions("system:user:edit")
    @Log(title = "修改用户设置", businessType = BusinessType.UPDATE)
    @PostMapping("/editbloginpost")
    @ResponseBody
    @RepeatSubmit
    public AjaxResult userBrowserLoginEditPost(@RequestParam Map<String, Object> params) {
        AjaxResult ajaxResult = new AjaxResult();
        if (params.get("infoItems") == null || params.get("infoItems") == ""){
        	return AjaxResult.error("缺少参数infoItems【对应实体类的json格式字符串】。");
        }
        try {
            ajaxResult= userInfoService.updateBrowserLogin(params);
        }catch (Exception e) {
            ajaxResult = AjaxResult.error(this.getExceptionMessage(e));
        }
        return ajaxResult;
    }

    /**
     * 修改密码——数据提交
     * @param upType 修改类型（"resetpwd":重置密码，无需提供原密码；"changepwd":修改密码，需要提供原密码）
     * @param userId 用户编号
     * @param newPwd 新用户密码
     * @param oldPwd 原用户密码，修改密码时需要提供，重置密码时可不提供
     * @return AjaxResult
     * @author DH-Xxj
     */
//    @RequiresPermissions("system:user:edit")
    @Log(title = "修改密码", businessType = BusinessType.UPDATE)
    @PostMapping("/editpwdpost")
    @ResponseBody
    @RepeatSubmit
    public AjaxResult userPassWordEditPost(@RequestParam Map<String, Object> params) {
        AjaxResult ajaxResult = new AjaxResult();
        try {
            ajaxResult= userInfoService.updateUserPassWord(params);
        }catch (Exception e) {
            ajaxResult = AjaxResult.error(this.getExceptionMessage(e));
        }
        return ajaxResult;
    }

    /**
     * 修改密码——本地批量
     * @throws Exception 
     */
    @GetMapping("/editpwdpostLocal")
    @ResponseBody
    public AjaxResult editpwdpostLocal() throws Exception {
    	
    	Map<String, Object> params = new HashMap<String, Object>();
    	
    	List<SysUserInfo> listSysUserInfo = userInfoService.queryUserList(params);
    	for(SysUserInfo sysUserInfo : listSysUserInfo) {
    		System.out.println(sysUserInfo.getUserId());
        	String userId = sysUserInfo.getUserId();
        	String newPwd = "123456";
    		userInfoService.updateUserPassWordLocal(userId, newPwd);
    	}
    	
        return AjaxResult.success();
    }

    /**
     * 修改二级密码——数据提交
     * @param upType 修改类型（"resetpwd":重置密码，无需提供原密码；"changepwd":修改密码，需要提供原密码）
     * @param userId 用户编号
     * @param newPwd2 新二级密码
     * @param oldPwd2 原二级密码，修改密码时需要提供，重置密码时可不提供
     * @return AjaxResult
     * @author DH-Xxj
     */
//    @RequiresPermissions("system:user:edit")
    @Log(title = "修改二级密码", businessType = BusinessType.UPDATE)
    @PostMapping("/editpwd2post")
    @ResponseBody
    @RepeatSubmit
    public AjaxResult userPassWord2EditPost(@RequestParam Map<String, Object> params) {
        AjaxResult ajaxResult = new AjaxResult();
        try {
            ajaxResult= userInfoService.updateUserPassWord2(params);
        }catch (Exception e) {
            ajaxResult = AjaxResult.error(this.getExceptionMessage(e));
        }
        return ajaxResult;
    }

    /**
     * 绑定用户档案
     * @param infoItems 对应实体类的json格式字符串，包含属性（userId ：用户编号，daNid ：档案入职信息nid号）
     * @return
     * @author DH-Xxj
     */
    @RequiresPermissions("system:user:edit")
    @Log(title = "绑定档案", businessType = BusinessType.UPDATE)
    @PostMapping("/relevantda")
    @ResponseBody
    @RepeatSubmit
    public AjaxResult updateUserDaNidPost(@RequestParam Map<String, Object> params) {
        AjaxResult ajaxResult = new AjaxResult();
        try {
            ajaxResult= userInfoService.updateUserDaNid(params);
        }catch (Exception e) {
            ajaxResult = AjaxResult.error(this.getExceptionMessage(e));
        }
        return ajaxResult;
    }

    /**
     * 删除用户
     * @param userInfoItems 必要参数：对应实体类的json格式字符串
     * @return AjaxResult
     * @author DH-Xxj
     */
    @RequiresPermissions("system:user:delete")
    @Log(title = "删除用户", businessType = BusinessType.DELETE)
    @PostMapping("/delete")
    @ResponseBody
    @RepeatSubmit
    public AjaxResult userInfoDelete(@RequestParam Map<String, Object> params) {
        AjaxResult ajaxResult = new AjaxResult();
        if (params.get("userInfoItems") == null || params.get("userInfoItems") == ""){
        	return AjaxResult.error("缺少参数userInfoItems【对应实体类的json格式字符串】。");
        }
        try {
            ajaxResult= userInfoService.deleteUserInfo(params);
        }catch (Exception e) {
            ajaxResult = AjaxResult.error(this.getExceptionMessage(e)); 
        }
        return ajaxResult;
    }
    
}